package br.com.searchpeople.activity;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.QuickContactBadge;
import android.widget.RadioButton;
import android.widget.Toast;
import br.com.searchpeople.R;
import br.com.searchpeople.asynctask.PostTask;
import br.com.searchpeople.service.GPSTracker;

public class CreatePostActivity extends Activity {

	private static final String ENDPOINT_URL = "http://10.5.18.163:3000/posts";
	//private final static String ENDPOINT_URL = "http://192.168.1.103:3000/api/v1/sessions.json";
	//private static final String ENDPOINT_URL = "http://10.0.2.2:3000/posts";
	//private final static String ENDPOINT_URL = "http://10.5.18.163:3000/api/v1/sessions.json";
	private static final int GALLERY = 1;
	private static final int CONTACT_DATA = 2;
	private static final int NEW_HEIGHT = 120;
	private static final int NEW_WIDTH = 120;
	private static final int RESULT_LOCATION = 3;
	
	private GPSTracker gps;
	private boolean customlocation = false;

	private Bitmap image = null;
	private Bitmap resizedBitmap = null;
	
	private String name;
	private String description;
	private String country;
	private String state;
	private String city;
	private double latitude;
	private double longitude;
	
	private QuickContactBadge quickContactBadge;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_createpost);
		
		quickContactBadge = (QuickContactBadge) findViewById(R.id.quickContactBadge1);
		quickContactBadge.setImageToDefault();
		quickContactBadge.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (image != null)
					image.recycle();
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				startActivityForResult(
						Intent.createChooser(intent, "Select Picture"), GALLERY);
			}
		});
	}

	public void identificationData(View v) {
		Intent intent = new Intent(this, IdentificationDataActivity.class);
		startActivityForResult(intent, CONTACT_DATA);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		
		
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			// Recupera imagem da galeria de fotos do android.
				case GALLERY:

					Uri mImageUri = data.getData();
					try {
						image = Media.getBitmap(this.getContentResolver(),
							mImageUri);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					resizedBitmap = resizeBitmap(image, NEW_HEIGHT, NEW_WIDTH);

					quickContactBadge.setImageBitmap(resizedBitmap);

					break;
			// Recupera dados da activity IdentificationDataActivity e insere os dados no banco de dados.	
				case CONTACT_DATA:
					
					String phone = data.getStringExtra("phone").toString();
					String email = data.getStringExtra("email").toString();
					name = ((EditText) findViewById(R.id.editview_name)).getText().toString();
					description = ((EditText) findViewById(R.id.editview_description)).getText().toString();
					country = ((EditText) findViewById(R.id.editview_country)).getText().toString();
					state = ((EditText) findViewById(R.id.editview_state)).getText().toString();
					city = ((EditText) findViewById(R.id.editview_city)).getText().toString();
					if(!customlocation) {
						getMyLocation();
					}
					String bitmapToString = BitMapToString(resizedBitmap);
					
					PostTask postTask = new PostTask(CreatePostActivity.this, name, description, country, state, city, phone, email, bitmapToString, latitude, longitude);
					
					postTask.execute(ENDPOINT_URL);

					finish();
					break;
					
				case RESULT_LOCATION:
					
					latitude = data.getExtras().getDouble("latitude");
					longitude = data.getExtras().getDouble("longitude");
					
					break;
				default:
					break;
			}
		}
	}

	// Redimensiona Bitmap para qualquer tamanho
	private Bitmap resizeBitmap(Bitmap bp, int newHeight, int newWidth) {

		float scaleHeight = ((float) newHeight) / bp.getHeight();
		float scaleWidth = ((float) newWidth) / bp.getWidth();

		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);

		Bitmap resizedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), matrix, true);
		return resizedBitmap;
	}

	private void createSpecificNotificationToast(String arg0) {
		Context context = getApplicationContext();
		CharSequence text = arg0;
		int duration = Toast.LENGTH_SHORT;
		Toast toast = Toast.makeText(context, text, duration);
		toast.show();
	}
	
	public String BitMapToString(Bitmap bitmap){
        ByteArrayOutputStream baos = new  ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
        byte [] b = baos.toByteArray();
        String temp = Base64.encodeToString(b, Base64.DEFAULT);
        return temp;
	}
	
	public void onRadioButtonClicked(View view) {
		boolean checked = ((RadioButton) view).isChecked();
		
		// Check which radio button was clicked
	    switch(view.getId()) {
	        case R.id.radio_my_location:
	        	Log.d("+++ mylocation +++", "********");
	            if (checked)
	            customlocation = false;
	            getMyLocation();
	            break;
	        case R.id.radio_set_location:
	        	Log.d("+++ setlocation +++", "____________");
	        	Intent i = null;
	            if (checked)
	            	customlocation = true;
	            	i = new Intent(this, CustomLocationActivity.class);
					startActivityForResult(i, RESULT_LOCATION);
	            break;
	    }

	}

	private void getMyLocation() {
		gps = new GPSTracker(CreatePostActivity.this);

        if(gps.canGetLocation()){
        	
        	latitude = gps.getLatitude();
        	longitude = gps.getLongitude();
     
        }else{
        	gps.showSettingsAlert();
        }
	}


}
